/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.app.controller;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.yanlight.Constants;
import com.yanlight.app.request.AlipayMemberAuthRequest;
import com.yanlight.app.request.AlipayProviderSignGrantRequest;
import com.yanlight.app.service.AlipayService;
import com.yanlight.support.alipay.AlipayConstants;
import com.yanlight.support.alipay.AlipayFactory;
import com.yanlight.util.CookieUtil;
import com.yanlight.util.EncryptUtil;
import com.yanlight.util.WebUtil;

/**
 *
 * @author haolw
 * @time 2017/07/21
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController {
    @Autowired
    private AlipayService alipayService;

    @RequestMapping("/memberAuth")
    public String alipayMemberAuth(AlipayMemberAuthRequest request) {
        String authCode = request.getAuthCode();
        if (StringUtils.isBlank(authCode)) {
            return Constants.NO_SERVICE_VIEW;
        }
        String redirectUrl = EncryptUtil.decodeBase64(request.getUrl());
        try {
            AlipayClient alipayClient = AlipayFactory.providerClient();
            AlipaySystemOauthTokenRequest authRequest = new AlipaySystemOauthTokenRequest();
            authRequest.setCode(authCode);
            authRequest.setGrantType(AlipayConstants.AUTH_GRANTTYPE_CODE);
            AlipaySystemOauthTokenResponse authResponse = alipayClient.execute(authRequest);
            String userId = authResponse.getUserId();
            if (StringUtils.isNotBlank(userId)) {
                CookieUtil.addCookie(Constants.ALIPAY_USER_ID, userId);
                return redirect(redirectUrl);
            } else {
                return Constants.NO_SERVICE_VIEW;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Constants.NO_SERVICE_VIEW;
        }
    }

    @RequestMapping("/providerSignGrant")
    public void providerSignGrant(HttpServletResponse httpResponse, AlipayProviderSignGrantRequest request) {
        String result = alipayService.signGrant(request).getResult();
        WebUtil.renderText(httpResponse, result);
        return;
    }

}
